package com.jack.xiaoer.web.controller;

import com.jack.xiaoer.util.AjaxResponse;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;
import java.util.Optional;

/**
 * Created by Jackaroo Zhang on 2018/12/10.
 */
public abstract class BaseController {

    protected AjaxResponse handleBindingResult(BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            return AjaxResponse.invalid(allErrors.get(0).getDefaultMessage());
        }
        return null;
    }

    protected AjaxResponse commonValidate(Optional optional, BindingResult bindingResult) {
        /* check parameter */
        if (!optional.isPresent()) {
            return AjaxResponse.invalid("请输入正确的参数");
        }
        if (bindingResult.hasErrors()) {
            return handleBindingResult(bindingResult);
        }

        return null;
    }

}
